#!/usr/bin/perl

use LWP::Simple;
use XML::Simple;
use Data::Dumper;
use File::Path;
use CGI;
use Net::FTP;

print CGI::header((-type=>'text/javascript'));

$ykey;
$myftplogin;
$myftppassword;

require 'password.txt';

my $form       = new CGI;

#my $origsearchword = 'star wars';
my $origsearchword = $form->param('searchword');

# get a version of the searchword that has spaces removed
my $saveword = $origsearchword;
$saveword =~ s/ /_/g;
$saveword =~ tr/A-Z/a-z/;
$saveword =~ s/[^A-Za-z0-9-_]//g;

$homedir = '/home/chadphil/public_html/windmeadow/';
$homedir = '/mnt/tc/wrk_school/al_building/';

# get an escapge version that can be used in the yahoo api
my $searchword = CGI->escape( $saveword );

if (-f $homedir . $saveword . ".html") {
   open(TMP, $homedir . "mosaic/" . $saveword . ".html" );
   while (<TMP>) {
     print $_;
   }
   exit;
}

_write_output( "Starting", $saveword );

my $time = "tmp/" . time();
mkpath( $time, 0 );
mkpath( $time . "/prep", 0 );

my $url = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=$ykey&query=$searchword&results=50&format=jpeg";
my $returncode = _get_images( $url, 1 );

if ($returncode eq 'error') {
   print "<B><FONT COLOR='red'>ERROR:</FONT></B><BR/> Over yahoo api rate limit or no search results were found";
   exit; 
}

_start_metapixel();


my $final_html = qq! This is what <B>$origsearchword</B> looks like <BR><BR> <A href="/mosaic/$saveword.png"><img src="/mosaic/thumb/$saveword.jpg"></A> <BR/> <BR/><A href="$mainimage"><BR/> Original:<BR/><img src="$ClickUrl"></A>!;
print $final_html;

 _write_output( $final_html, $saveword );

exit;



sub _write_output {
    my $output    = shift;
    my $seachword = shift;
    open( TMP, "> " . $homedir . "mosaic/" . $saveword . ".html" );
    print TMP $output;
    close(TMP);
}

sub _ftp_output {
    my $filename = shift;
    return;

    my $ftp = Net::FTP->new( "chadphillips.org", Debug => 1 );
    $ftp->login( $myftplogin, $myftppassword ) || die "cant login", $ftp->message;
    $ftp->binary() || die "cant change to binary", $ftp->message;
    $ftp->cwd("/public_html/windmeadow/mosaic") || die "cant change directory", $ftp->message;

    $ftp->put($filename) || die "cant put file", $ftp->message;
    $ftp->quit;
}

sub _get_images {
    my $url        = shift;
    my $writecount = shift;

    _write_output( " Preparing to download images ", $saveword );

    # make the request
    my $results = get $url || die "Web services request failed: $!";
    my $ref     = XMLin($results);
    my $flag    = 1;
    my $count   = 0;
    my $writefile = 0;

    if ( $results =~ /errors were detected/ || $ref->{totalResultsReturned} < 1  ) {
       return 'error';  
    } 

    # save the first image to be used as the reference image by metapixel
    if ( $writecount < 2 ) {
        $mainimage = $ref->{Result}->[0]->{RefererUrl};
        $summary = $ref->{Result}->[0]->{Summary};
        $summary = $ref->{Result}->[0]->{Summary};
        $ClickUrl = $ref->{Result}->[0]->{Thumbnail}->{Url};
        getstore( $ref->{Result}->[0]->{Thumbnail}->{Url}, $time . "/mainimage.jpg" );
        #getstore( $ref->{Result}->[0]->{ClickUrl}, $time . "/mainimage.jpg" );

    }

    while ($flag) {
        if ( $ref->{Result}->[$count]->{Thumbnail}->{Url} ) {
            $ref->{Result}->[$count]->{Thumbnail}->{Url} . "\n";
            getstore(
                $ref->{Result}->[$count]->{Thumbnail}->{Url},
                $time . "/image" . $writecount . ".jpg"
            );
            if ( $writefile > 40) {
               _write_output( " Loading image $writecount ", $saveword );
               $writefile = 0;
            }
            $writefile++;
        }
        else {
            $flag = 0;
        }
        $count++;
        $writecount++;
    }
}

sub _start_metapixel {
    _write_output( "Prepping image files", $saveword );

    my $a = system( "export PATH=.:$PATH;" . $homedir . "cgi-bin/metapixel-prepare --width=32 --height=32 ./$time ./$time/prep >> /dev/null");
    if ( $a ) {
         _send_error( $a );
    }

    _write_output( "Creating Mosaic", $saveword );
    $a = system( "export PATH=.:$PATH;" . $homedir . "cgi-bin/metapixel -s 16 -w 32 -h 32 -d 1 -a 20 --metric=subpixel --metapixel  ./$time/mainimage.jpg " . $homedir . "mosaic/$saveword.png --library ./$time/prep >> /dev/null");
    if ( $a ) {
         _send_error( $a );
    }

    _write_output( "Scaling mosaic", $saveword );
    $a = system("/usr/bin/convert -scale 500  " . $homedir . "mosaic/$saveword.png " . $homedir . "mosaic/thumb/$saveword.jpg");
    if ( $a ) {
         _send_error( $a );
    }

}

sub _send_error  {
   my $error = shift;

   my $final_html = qq! Sorry there was an error during processing. Error code = $error !;
   print $final_html;
   _write_output( $final_html, $saveword );
   exit;
}

